package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.itheima.pojo.Article;
import com.itheima.pojo.Category;
import com.itheima.pojo.Result;
import com.itheima.service.ICategoryService;
import com.itheima.utils.ThreadLocalUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/category")
@RequiredArgsConstructor
@Validated
public class CategoryController {

    private  final ICategoryService categoryService;


    @PostMapping
    public Result<String> addCategory(@RequestBody @Validated(Category.add.class) Category category){
        //设置属性
        category.setCreateTime(LocalDateTime.now());
        category.setUpdateTime(LocalDateTime.now());
        Map<String,Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        category.setCreateUser(userId);
        categoryService.save(category);
        return Result.success();

    }
    @GetMapping
    public Result<List<Category>> queryCategoryList(){
        //获取用户id
        Map<String,Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        LambdaQueryWrapper<Category> wrapper = new QueryWrapper<Category>().lambda()
                .eq(Category::getCreateUser,userId);
        List<Category> categoryList = categoryService.list(wrapper);
        return Result.success(categoryList);
    }
    @GetMapping("/detail")
    public Result<Category> categoryDetail(@RequestParam Integer id){
        Category category = categoryService.getById(id);
        return Result.success(category);

    }
    @PutMapping
    public Result<String> updateCategory(@RequestBody @Validated(Category.update.class) Category category){
        //设置更新时间
        category.setUpdateTime(LocalDateTime.now());
        categoryService.updateById(category);
        return Result.success();

    }
    @DeleteMapping
    public Result<String> deleteCategoryById(@RequestParam Integer id){
        categoryService.removeById(id);
        return Result.success();

    }

}
